package com.ruoyi.pos.web.service.impl;

import com.ruoyi.common.enums.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.qugongbao.QugongbaoUtils;
import com.ruoyi.pos.api.utils.CommonUtils;
import com.ruoyi.pos.web.domain.*;
import com.ruoyi.pos.web.mapper.*;
import com.ruoyi.pos.web.service.ITUserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户基础数据Service业务层处理
 *
 * @author ruoyi
 * @date 2021-11-10
 */
@Service
public class TUserInfoServiceImpl implements ITUserInfoService {

    private static final Logger log = LoggerFactory.getLogger(TUserInfoServiceImpl.class);

    @Autowired
    private TUserInfoMapper tUserInfoMapper;
    @Autowired
    private TUserTeamInfoMapper userTeamInfoMapper;
    @Autowired
    private TStatisticInfoMapper statisticInfoMapper;
    @Autowired
    private TGradeInfoMapper gradeInfoMapper;
    @Autowired
    private TBankInfoMapper bankInfoMapper;

    @Autowired
    private CommonUtils commonUtils;
    @Autowired
    QugongbaoUtils qugongbaoUtils;

    /**
     * 查询用户基础数据
     *
     * @param userId 用户基础数据主键
     * @return 用户基础数据
     */
    @Override
    public TUserInfo selectTUserInfoByUserId(String userId) {
        TUserInfo user = tUserInfoMapper.selectTUserInfoByUserId(userId);
        if (StringUtils.isNotEmpty(user.getSuperiorUserId())) {
            TUserInfo supUser = tUserInfoMapper.selectTUserInfoByUserId(user.getSuperiorUserId());
            user.setSupUserPhone(supUser.getUserPhone()); //上级用户手机号
        }
        TUserTeamInfo teamMapper = new TUserTeamInfo();
        teamMapper.setUserId(user.getUserId());
        List<TUserTeamInfo> teamList = userTeamInfoMapper.selectTUserTeamInfoList(teamMapper);
        user.setTeamSum(teamList.stream().filter(team -> TeamTypeEnum.TEAM.getCode().equals(team.getTeamType())).collect(Collectors.toList()).size()); //团队总数
        List<TUserTeamInfo> directlyList = teamList.stream().filter(team -> TeamTypeEnum.DIRECTLY.getCode().equals(team.getTeamType())).collect(Collectors.toList());
        user.setDirectlyNum(directlyList.size()); //直营总数
        List<String> userIds = directlyList.stream().map(TUserTeamInfo::getUserId).collect(Collectors.toList());
        TStatisticInfo info = null;
        if (userIds.size() > 0) {
            info = statisticInfoMapper.selectTStatisticInfoByUserIds(userIds, "", "", "");
            user.setDirectlyTerminalNum(info == null ? BigDecimal.ZERO : info.getMyTerminalNum()); //直营终端数
        }
        userIds = new ArrayList<String>();
        userIds.add(userId);
        info = statisticInfoMapper.selectTStatisticInfoByUserIds(userIds, null, null, null);
        user.setOwnTerminalNum(info == null ? BigDecimal.ZERO : info.getMyTerminalNum()); //我的终端数
        user.setUserStatusShow(YesOrNoEnums.getEnumsByCode(user.getUserStatus()).getUserStatus());
        if (YesOrNoEnums.YES.getCode().equals(user.getAutonymType())) {
            if (AuditStatusEnum.PASS_AUDIT.getCode().equals(user.getAuditStatus())) {
                user.setAutonymTypeShow(YesOrNoEnums.YES.getValue());
            } else {
                user.setAutonymTypeShow(YesOrNoEnums.NO.getValue());
            }
        } else {
            user.setAutonymTypeShow(YesOrNoEnums.NO.getValue());
        }

        //翻译银行信息
        if (StringUtils.isNotEmpty(user.getBankId())) {
            TBankInfo bank = bankInfoMapper.selectTBankInfoByBankId(user.getBankId());
            user.setBankName((null == bank ? new TBankInfo() : bank).getBankName());
        }
        TGradeInfo grade = gradeInfoMapper.selectTGradeInfoById(user.getGradeId());
        user.setGradeCode(grade.getGradeCode());
        return user;
    }

    /**
     * 查询用户基础数据列表
     *
     * @param tUserInfo 用户基础数据
     * @return 用户基础数据
     */
    @Override
    public List<TUserInfo> selectTUserInfoList(TUserInfo tUserInfo) {
        List<TUserInfo> userList = tUserInfoMapper.selectTUserInfoListForWeb(tUserInfo);
        Optional.ofNullable(userList).ifPresent(users -> {
            users.stream().forEach(user -> {
                user.setUserStatusShow(YesOrNoEnums.getEnumsByCode(user.getUserStatus()).getUserStatus());
                if (YesOrNoEnums.YES.getCode().equals(user.getAutonymType())) {
                    if (AuditStatusEnum.PASS_AUDIT.getCode().equals(user.getAuditStatus())) {
                        user.setAutonymType(YesOrNoEnums.YES.getValue());
                    } else {
                        user.setAutonymType(YesOrNoEnums.NO.getValue());
                    }
                } else {
                    user.setAutonymType(YesOrNoEnums.NO.getValue());
                }
            });
        });
        return userList;
    }

    /**
     * 查询用户基础数据列表
     *
     * @param tUserInfo 用户基础数据
     * @return 用户基础数据
     */
    @Override
    public List<TUserInfo> selectTUserInfoListForTrans(TUserInfo tUserInfo) {
        List<TUserInfo> userList = tUserInfoMapper.selectTUserInfoListForWeb(tUserInfo);
        List<TUserInfo> resultList = userList.stream().filter(bean ->YesOrNoEnums.YES.getCode().equals(bean.getAutonymType()) && AuditStatusEnum.PASS_AUDIT.getCode().equals(bean.getAuditStatus())).collect(Collectors.toList());
        return resultList;
    }

    /**
     * 新增用户基础数据
     *
     * @param tUserInfo 用户基础数据
     * @return 结果
     */
    @Override
    public int insertTUserInfo(TUserInfo tUserInfo) {
        tUserInfo.setCreateTime(DateUtils.getNowDate());
        return tUserInfoMapper.insertTUserInfo(tUserInfo);
    }

    /**
     * 修改用户基础数据
     *
     * @param tUserInfo 用户基础数据
     * @return 结果
     */
    @Override
    public int updateTUserInfo(TUserInfo tUserInfo) throws Exception {
        TUserInfo oldUser = tUserInfoMapper.selectTUserInfoByUserId(tUserInfo.getUserId());
        if (StringUtils.isNotEmpty(tUserInfo.getMemberNo())
                && StringUtils.isNotEmpty(tUserInfo.getBankCardMark())
                && !tUserInfo.getBankCardMark().equalsIgnoreCase(oldUser.getBankCardMark())) { //说明变更了银行卡号，需要同步变更到趣工宝
            try {
                qugongbaoUtils.updateBankCard(oldUser.getMemberNo(), tUserInfo.getBankCardMark());
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("修改银行卡号调用趣工宝变更接口失败，请联系管理员！");
            }
        }
        return tUserInfoMapper.updateTUserInfo(tUserInfo);
    }

    /**
     * 批量删除用户基础数据
     *
     * @param userIds 需要删除的用户基础数据主键
     * @return 结果
     */
    @Override
    public int deleteTUserInfoByUserIds(String[] userIds) {
        return tUserInfoMapper.deleteTUserInfoByUserIds(userIds);
    }

    /**
     * 删除用户基础数据信息
     *
     * @param userId 用户基础数据主键
     * @return 结果
     */
    @Override
    public int deleteTUserInfoByUserId(String userId) {
        return tUserInfoMapper.deleteTUserInfoByUserId(userId);
    }

    @Override
    @Transactional
    public int changeUserStatus(TUserInfo tUserInfo) throws Exception {
        TUserInfo user = tUserInfoMapper.selectTUserInfoByUserId(tUserInfo.getUserId());
        user.setUserStatus(tUserInfo.getUserStatus());
        tUserInfoMapper.updateTUserInfo(user);
        return tUserInfoMapper.updateTUserInfo(user);
    }

    @Override
    @Transactional
    public int changeUserTeam(TUserInfo tUserInfo) throws Exception {
        if (StringUtils.isEmpty(tUserInfo.getSuperiorUserId())) {
            throw new RuntimeException("上级用户id不能为空");
        }
        //1、先处理直属上级关系
        Date date = DateUtils.getNowDate();
        TUserInfo oleUser = tUserInfoMapper.selectTUserInfoByUserId(tUserInfo.getUserId());
        if (StringUtils.isNotEmpty(oleUser.getSuperiorUserId())) { //说明上级不为空，则先删除上级的直属关系
            userTeamInfoMapper.deleteTUserTeamInfoByUsers(oleUser.getSuperiorUserId(), oleUser.getUserId(), TeamTypeEnum.DIRECTLY.getCode());
        }
        TUserTeamInfo teamNew = commonUtils.generateUserTeamInfo(
                tUserInfo.getSuperiorUserId(),
                tUserInfo.getUserId(),
                TeamTypeEnum.DIRECTLY.getCode(),
                date);
        userTeamInfoMapper.insertTUserTeamInfo(teamNew); //直接建立一个新的直属关系
        //下面就直接操作团队关系，不再关注直属关系的转移
        TUserInfo supUser = tUserInfoMapper.selectTUserInfoByUserId(tUserInfo.getSuperiorUserId());
        tUserInfo.setSuperiorUserName(supUser.getUserName());
        //2、先查询自己现在所属的团队关系
        TUserTeamInfo mapper = new TUserTeamInfo();
        mapper.setSubUserId(tUserInfo.getUserId());
        mapper.setTeamType(TeamTypeEnum.TEAM.getCode());
        List<TUserTeamInfo> nowSupTeam = userTeamInfoMapper.selectTUserTeamInfoList(mapper);
        //3、获取旧的上级userId集合
        List<String> oldSupUsers = nowSupTeam.stream()
                .filter(team -> !team.getUserId().equals(tUserInfo.getUserId()))
                .collect(Collectors.toList())
                .stream()
                .map(TUserTeamInfo::getUserId)
                .distinct()
                .collect(Collectors.toList());
        log.info("我所在的旧的上级成员用户集合：" + oldSupUsers);
        ///4、获取我的下级userId集合
        mapper = new TUserTeamInfo();
        mapper.setSubUserId(tUserInfo.getUserId());
        mapper.setTeamType(TeamTypeEnum.TEAM.getCode());
        List<TUserTeamInfo> myTeam = userTeamInfoMapper.selectTUserTeamInfoList(mapper);
        List<String> mySubUsers = myTeam.stream()
                .map(TUserTeamInfo::getSubUserId)
                .distinct()
                .collect(Collectors.toList());
        log.info("我的下级成员用户集合：" + mySubUsers);
        //5、获取新的上级所在团队集合
        mapper = new TUserTeamInfo();
        mapper.setSubUserId(tUserInfo.getSuperiorUserId());
        mapper.setTeamType(TeamTypeEnum.TEAM.getCode());
        List<TUserTeamInfo> newSupTeam = userTeamInfoMapper.selectTUserTeamInfoList(mapper);
        List<String> newSupUsers = newSupTeam.stream()
                .map(TUserTeamInfo::getUserId)
                .distinct()
                .collect(Collectors.toList());
        log.info("我的新上级所在的团队成员用户集合：" + mySubUsers);
        //6、删除我的团队在旧的上级团队中的所有关系
        mySubUsers.stream().forEach(mySubUser -> {
            oldSupUsers.stream().forEach(oldUser -> {
                userTeamInfoMapper.deleteTUserTeamInfoByUsers(oldUser, mySubUser, TeamTypeEnum.TEAM.getCode());
            });
        });
        //7、插入我的团队在新的上级所在团队人员的团队关系
        mySubUsers.stream().forEach(mySubUser -> {
            newSupUsers.stream().forEach(newUserUser -> {
                TUserTeamInfo newteam = commonUtils.generateUserTeamInfo(
                        newUserUser,
                        mySubUser,
                        TeamTypeEnum.TEAM.getCode(),
                        date);
                userTeamInfoMapper.insertTUserTeamInfo(newteam);
            });
        });
        return tUserInfoMapper.updateTUserInfo(tUserInfo);
    }

    @Override
    public List<TGradeInfo> queryGradeInfoList() throws Exception {
        List<TGradeInfo> gradeList = gradeInfoMapper.selectTGradeInfoList(new TGradeInfo());
        gradeList.remove(gradeList.size() - 1);
        gradeList.remove(0);
        return gradeList;
    }

    @Override
    public List<TUserInfo> selectTUserInfoCheckList(TUserInfo tUserInfo) {
        tUserInfo.setAutonymType(YesOrNoEnums.YES.getCode());
        tUserInfo.setAuditStatus(AuditStatusEnum.WAIT_AUDIT.getCode());
        List<TUserInfo> userList = tUserInfoMapper.selectTUserInfoListForCheck(tUserInfo);
        Optional.ofNullable(userList).ifPresent(users -> {
            users.stream().forEach(user -> {
                //user.setUserStatus(YesOrNoEnums.getEnumsByCode(user.getUserStatus()).getUserStatus());
                user.setAutonymType(YesOrNoEnums.getEnumsByCode(user.getAutonymType()).getValue());
                user.setAuditStatusDescribe(AuditStatusEnum.getEnumsByCode(user.getAuditStatus()).getValue());

            });
        });
        return userList;
    }

    //审核通过
    @Override
    @Transactional
    public int checkPass(TUserInfo userInfo) throws Exception {
        TUserInfo newUser = tUserInfoMapper.selectTUserInfoByUserId(userInfo.getUserId());
        newUser.setAuditStatus(AuditStatusEnum.PASS_AUDIT.getCode());
        //System.out.println("---------------------" + userInfo.getUserId());
        return tUserInfoMapper.updateTUserInfo(newUser);
    }

    //审核不通过
    @Override
    @Transactional
    public int checkRefuse(TUserInfo userInfo) {
        TUserInfo newUser = tUserInfoMapper.selectTUserInfoByUserId(userInfo.getUserId());
        newUser.setAuditStatus(AuditStatusEnum.REFUSE_AUDIT.getCode());
        newUser.setAuditStatusDescribe(userInfo.getAuditStatusDescribe());
        newUser.setAutonymType(YesOrNoEnums.NO.getCode());
        //System.out.println(userInfo.getAuditStatusDescribe() + "===============================" + userInfo.getUserId());
        return tUserInfoMapper.updateTUserInfo(newUser);
    }

    @Override
    public List<TUserInfo> merchantList(TUserInfo userInfo) {
        return tUserInfoMapper.merchantList(userInfo);
    }

    //变更趣工宝银行卡
    @Override
    @Transactional
    public boolean updateBankCard(TUserInfo userInfo) throws Exception {
        TUserInfo newUser = tUserInfoMapper.selectTUserInfoByUserId(userInfo.getUserId());
        if (StringUtils.isNotEmpty(newUser.getMemberNo()) && StringUtils.isNotEmpty(newUser.getBankCardMark())) {
            return qugongbaoUtils.updateBankCard(newUser.getMemberNo(), newUser.getBankCardMark());
        } else {
            return false;
        }
    }
}
